require('oneapm');

var mmlog=require("./sever/mmlog");
var log=mmlog.root("app");

//系统模块
var express = require('express');
var path = require('path');
var http = require("http");
var fs = require("fs");

//第三方模块
var multiparty = require('connect-multiparty');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//业务应用模块
var _config=require("./sever/config");


//var _dbAgent = require("./sever/db/agent");


var app = express(),
	isInstalled=false;

/**
 * 设置模板引擎
 */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//配置日志处理模块
app.use(mmlog.call().connectLogger(mmlog.call().getLogger("http"), { level: 'auto' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(cookieParser());

/**
 * 静态资源路径映射、便于访问静态资源文件
 */
app.use(express.static("client"));
app.use("/output",express.static("output"));
app.use("/res", express.static("client/common/resources"));
app.use("/plugs", express.static("client/plugins"));
app.use("/vendor", express.static("client/common/vendor"));


var sever = http.createServer(app);
sever.listen(80);

/**
 *异常捕获、由于Node的单线程异步编程特性、对于未知的异常会导致整个项目崩溃、需要捕获所有的异常信息
 * 当前是一种替代方法、
 * @author daoxiaozhang
 */
process.on('uncaughtException', function (err) {
  //打印出错误
  log.error(err);
  //打印出错误的调用栈方便调试
  log.error(err.stack);
});

var _dbAgent=null;


/**
 *  加载配置信息
 *  加载完成执行后续操作
 */
_config.init(function(_self,data){
	if(_self!=-1){
		log.debug("配置文件已经初始化完成、开始初始化服务");
		log.debug("微信服务...");
		var _wechat = require("./sever/channel/weixin");
		_wechat.init(app, express,_self);
		log.debug("邮件服务...");
		var _mail=require("./sever/channel/mail");
		_mail.init(data.email);
		log.debug("WebSocket服务...");
		log.debug("加载插件");

		//动态加载插件
		require("./sever/pluginManager").init(function(data){
			if(data!=-1){
				require("./sever/socket").init(sever,app);
				app.use("/message", require("./routes/message"));
				app.use("/session", require("./routes/session"));
				app.use("/agent", require("./routes/agent"));
				app.use("/sys", require("./routes/sys"));
				app.use("/ticket", require("./routes/ticket"));
			}else{
				data.forEach(function(item){
					if(item.router){
						app.use("/"+item.uuid,require("../client/plugins/"+item.router))
					}
				});
			}
		});
		_dbAgent=require("./sever/db/agent");
		isInstalled=true;
	}
})


/**
 * 暂时移除该方法 
 */
if(!fs.existsSync("./views/install.ejs")){
	wechat.init(app, express);
}else{
	log.info("系统暂未安装配置完成...");
}

/**
 * 访问系统
 * 新部署的项目将会跳转到安装界面
 * 否则跳转到登录界面
 */
app.get('/', function(req, res) {
	if(!isInstalled){
		res.redirect("/install");
	}else{
		res.render("login");
	}
});

/**
 * 静态文本资源访问 
 */
app.get("/*.txt",function(req,res){
	res.sendFile(__dirname+"/"+req.params[0]+".txt");
});

/**
 *访问安装界面 
 */
app.get('/install', function(req, res) {
	res.render("install");
});

/**
 * 访问登录界面
 */
app.get('/login', function(req, res) {
	res.render("login", {
		title: "登录页面"
	});
});

/**
 * 登录接口、
 * 
 */
app.post("/login", function(req, res) {
	var data = req.body;
	_dbAgent.login(data, function(value) {
		var b=require("./sever/config").business();
		var bs=[];
		 for(var a in b){
		 	bs.push(b[a]);
		 }
		if (value && value.length) {
			res.render("index", {
				title: data.name,
				jobId: data.name,
				host:req.headers.host,
				business:bs,
				role:value[0].ROLE
			});
		} else {
			log.info("客户端登陆:",req.connection.remoteAddress);
			res.render("error", {
				message: "登陆失败",
				error: "坐席不存在"
			})
		}
	})
})

/*
 * 安装界面完成后调用的start接口、用于加载所有的功能
 */
app.get("/start", function(req, res) {
	log.debug("安装完成!请继续使用");
	var _wechat = require("./sever/channel/weixin");
	_wechat.init(app, express,_self);
	var _mail=require("./sever/channel/mail");
	_mail.init(_self);
	var socket = require("./sever/socket");
	_dbAgent=require("./sever/db/agent");
	app.use("/message", require("./routes/message"));
	app.use("/session", require("./routes/session"));
	app.use("/agent", require("./routes/agent"));
	app.use("/sys", require("./routes/sys"));
	app.use("/ticket", require("./routes/ticket"));
	socket.init(sever,app);
	isInstalled=true;
	fs.rename("./views/install.ejs","./views/install-end.ejs");
	res.json({});
})

/**
 * 文件上传接口
 */
app.post("/upload",multiparty(), function(req,res){
	var _ufile=req.files.ufile,
		_host=req.headers.host;
	fs.readFile(_ufile.path,function(error,data){
		if(!error){
			log.info("临时文件读取成功")
			fs.writeFile("./output/"+_ufile.name,data,function(error,_data){
				if(error)
					log.error("文件写入失败:\n",error);
				var fp=req.protocol+"://"+_host+"/output/"+_ufile.name;
				res.type("application/json");
				res.send({status:"0",content:fp});
			})
		}else{
			log.error("文件上传失败:\n",error);
		}
	})
});

app.post("/online/i/plugin",function(req){
	var p=req.body.path;
	if(p){
		var writestream = fs.createWriteStream("./client/plugins/monitor.zip");
	    http.get(p, function (res) {
	       res.pipe(writestream);
	    });
	    writestream.on('finish', function () {
	    	console.log("下载完成");
	    });
	}
})

module.exports = app;